import { computed, nextTick, ref, shallowRef } from 'vue';
import type { RouteRecordRaw } from 'vue-router';
import { defineStore } from 'pinia';
import { useBoolean } from '@sa/hooks';
import type { CustomRoute, ElegantConstRoute, LastLevelRouteKey, RouteKey, RouteMap } from '@elegant-router/types';
import { SetupStoreId } from '@/enum';
import { router } from '@/router';
import { createStaticRoutes, getAuthVueRoutes } from '@/router/routes';
import { ROOT_ROUTE } from '@/router/routes/builtin';
import { getRouteName, getRoutePath } from '@/router/elegant/transform';
import { fetchGetConstantRoutes, fetchGetUserRoutes, fetchIsRouteExist } from '@/service/api';
import { fetchGetAppNav } from '@/service/api/user';
import { getCodeData } from '@/admin/api/common';
import { getFormatRoutes } from '@/utils/route';
import { useAuthStore } from '../auth';
import { useTabStore } from '../tab';
import {
  filterAuthRoutesByRoles,
  getBreadcrumbsByRoute,
  getCacheRouteNames,
  getGlobalMenusByAuthRoutes,
  getSelectedMenuKeyPathByKey,
  isRouteExistByRouteName,
  sortRoutesByOrder,
  transformMenuToSearchMenus,
  updateLocaleOfGlobalMenus
} from './shared';
import { getNavInfo } from '@admin/api/common.js';
import { layouts, views } from '../elegant/imports';

export const useRouteStore = defineStore(SetupStoreId.Route, () => {
  const authStore = useAuthStore();
  const tabStore = useTabStore();
  const { bool: isInitConstantRoute, setBool: setIsInitConstantRoute } = useBoolean();
  const { bool: isInitAuthRoute, setBool: setIsInitAuthRoute } = useBoolean();

  /**
   * Auth route mode
   *
   * It recommends to use static mode in the development environment, and use dynamic mode in the production
   * environment, if use static mode in development environment, the auth routes will be auto generated by plugin
   * "@elegant-router/vue"
   */
  const authRouteMode = ref(import.meta.env.VITE_AUTH_ROUTE_MODE);

  /** Home route key */
  const routeHome = ref(import.meta.env.VITE_ROUTE_HOME);

  /**
   * Set route home
   *
   * @param routeKey Route key
   */
  function setRouteHome(routeKey: LastLevelRouteKey) {
    routeHome.value = routeKey;
  }

  /** constant routes */
  const constantRoutes = shallowRef<ElegantConstRoute[]>([]);

  function addConstantRoutes(routes: ElegantConstRoute[]) {
    const constantRoutesMap = new Map<string, ElegantConstRoute>([]);

    routes.forEach(route => {
      constantRoutesMap.set(route.name, route);
    });

    constantRoutes.value = Array.from(constantRoutesMap.values());
  }

  /** auth routes */
  const authRoutes = shallowRef<ElegantConstRoute[]>([]);

  // 接口路由
  const apiRoutes = ref<any[]>([]);

  /**
   * 添加权限路由
   *
   * 该方法用于将传入的权限路由数组转换为 Map，以路由名称为 key，路由对象为 value， 然后再将 Map 中的所有路由对象赋值给 authRoutes，实现去重和快速查找。
   *
   * @param routes 权限路由数组
   */
  function addAuthRoutes(routes: ElegantConstRoute[]) {
    const authRoutesMap = new Map<string, ElegantConstRoute>([]);

    routes.forEach(route => {
      authRoutesMap.set(route.name, route);
    });

    authRoutes.value = Array.from(authRoutesMap.values());
  }

  const removeRouteFns: (() => void)[] = [];

  /** Global menus */
  const menus = ref<App.Global.Menu[]>([]);
  const searchMenus = computed(() => transformMenuToSearchMenus(menus.value));
  const allMenus = ref<App.Global.Menu[]>([]);
  const allSearchMenus = computed(() => transformMenuToSearchMenus(allMenus.value));

  /** Get global menus */
  function getGlobalMenus(routes: ElegantConstRoute[]) {
    menus.value = getGlobalMenusByAuthRoutes(routes);
    allMenus.value = getGlobalMenusByAuthRoutes(routes, true);
  }

  /** Update global menus by locale */
  function updateGlobalMenusByLocale() {
    menus.value = updateLocaleOfGlobalMenus(menus.value);
  }

  /** Cache routes */
  const cacheRoutes = ref<RouteKey[]>([]);

  /**
   * Exclude cache routes
   *
   * for reset route cache
   */
  const excludeCacheRoutes = ref<RouteKey[]>([]);

  /**
   * Get cache routes
   *
   * @param routes Vue routes
   */
  function getCacheRoutes(routes: RouteRecordRaw[]) {
    cacheRoutes.value = getCacheRouteNames(routes);
  }

  // 根据id获取当前路由
  function getRouteById(id: string) {
    return allSearchMenus.value.find((i: any) => {
      return i.id == id
    })
  }

  /**
   * Reset route cache
   *
   * @default router.currentRoute.value.name current route name
   * @param routeKey
   */
  async function resetRouteCache(routeKey?: RouteKey) {
    const routeName = routeKey || (router.currentRoute.value.name as RouteKey);

    excludeCacheRoutes.value.push(routeName);

    await nextTick();

    excludeCacheRoutes.value = [];
  }

  /** Global breadcrumbs */
  const breadcrumbs = computed(() => getBreadcrumbsByRoute(router.currentRoute.value, menus.value));

  /** Reset store */
  async function resetStore() {
    const routeStore = useRouteStore();

    routeStore.$reset();

    resetVueRoutes();

    // after reset store, need to re-init constant route
    await initConstantRoute();
  }

  /** Reset vue routes */
  function resetVueRoutes() {
    removeRouteFns.forEach(fn => fn());
    removeRouteFns.length = 0;
  }

  /** init constant route */
  async function initConstantRoute() {
    if (isInitConstantRoute.value) return;

    const staticRoute = createStaticRoutes();

    addConstantRoutes(staticRoute.constantRoutes);

    handleConstantAndAuthRoutes();

    setIsInitConstantRoute(true);
  }

  /** Init auth route */
  async function initAuthRoute() {
    // check if user info is initialized
    if (!authStore.userInfo.code) {
      await authStore.initUserInfo();
    }

    await initDynamicAuthRoute();

    tabStore.initHomeTab();
  }

  /** Init static auth route */
  function initStaticAuthRoute() {
    const { authRoutes: staticAuthRoutes } = createStaticRoutes();

    if (authStore.isStaticSuper) {
      addAuthRoutes(staticAuthRoutes);
    } else {
      const filteredAuthRoutes = filterAuthRoutesByRoles(staticAuthRoutes, []);

      addAuthRoutes(filteredAuthRoutes);
    }

    handleConstantAndAuthRoutes();

    setIsInitAuthRoute(true);
  }

  // 获取接口动态路由
  function getApiRoutes() {
    return getFormatRoutes(apiRoutes.value)
  }

  /** Init dynamic auth route */
  async function initDynamicAuthRoute() {
    const codeData = await getCodeData();
    // 处理码表加载
    const dics = codeData.data;
    const CodeSource: any = {};
    if (dics && dics.length) {
      dics.forEach((dic: any) => {
        CodeSource[dic.codeDataTypeId] = dic.codeList.sort((pre: any, next: any) => {
          return pre.orderId >= next.orderId ? 1 : -1;
        });
      });
      (window as any).$CodeSource = CodeSource;
      localStorage.setItem('$CodeSource', JSON.stringify(CodeSource));
    }
    const { data: data } = await fetchGetAppNav({
      appId: (window as any).g.appId
    });
    apiRoutes.value = JSON.parse(JSON.stringify(data))
    const routes = getApiRoutes();
    // 首页
    const home = import.meta.env.VITE_ROUTE_HOME;
    // 路由去重
    addAuthRoutes([...routes]);
    handleConstantAndAuthRoutes();

    setRouteHome(home);

    handleUpdateRootRouteRedirect(home);

    setIsInitAuthRoute(true);
  }

  /**
   * 处理常量路由和权限路由
   *
   * 该方法会将 constantRoutes 和 authRoutes 合并，进行排序后，生成 vue 可用的路由格式， 然后重置 vue 路由表，并将新的路由添加到 vue-router 中。
   * 同时会根据合并后的路由生成全局菜单和缓存路由列表。
   */
  function handleConstantAndAuthRoutes() {
    const allRoutes = [...constantRoutes.value, ...authRoutes.value];

    const sortRoutes = sortRoutesByOrder(allRoutes);

    // 转换为vue路由
    const vueRoutes = getAuthVueRoutes(sortRoutes);

    resetVueRoutes();
    // 添加路由到vue-router
    addRoutesToVueRouter(vueRoutes);
    // 设置菜单
    getGlobalMenus(sortRoutes);
    // 设置缓存路由
    getCacheRoutes(vueRoutes);
  }

  /**
   * Add routes to vue router
   *
   * @param routes Vue routes
   */
  function addRoutesToVueRouter(routes: RouteRecordRaw[]) {
    routes.forEach(route => {
      const removeFn = router.addRoute(route);
      addRemoveRouteFn(removeFn);
    });
  }

  /**
   * Add remove route fn
   *
   * @param fn
   */
  function addRemoveRouteFn(fn: () => void) {
    removeRouteFns.push(fn);
  }

  /**
   * Update root route redirect when auth route mode is dynamic
   *
   * @param redirectKey Redirect route key
   */
  function handleUpdateRootRouteRedirect(redirectKey: LastLevelRouteKey) {
    const redirect = getRoutePath(redirectKey);

    if (redirect) {
      const rootRoute: CustomRoute = { ...ROOT_ROUTE, redirect };

      router.removeRoute(rootRoute.name);

      const [rootVueRoute] = getAuthVueRoutes([rootRoute]);

      router.addRoute(rootVueRoute);
    }
  }

  /**
   * Get is auth route exist
   *
   * @param routePath Route path
   */
  async function getIsAuthRouteExist(routePath: RouteMap[RouteKey]) {
    const routeName = getRouteName(routePath);

    if (!routeName) {
      return false;
    }

    const { data } = await fetchIsRouteExist(routeName);

    return data;
  }

  /**
   * Get selected menu key path
   *
   * @param selectedKey Selected menu key
   */
  function getSelectedMenuKeyPath(selectedKey: string) {
    return getSelectedMenuKeyPathByKey(selectedKey, menus.value);
  }

  async function onRouteSwitchWhenLoggedIn() {
    authStore.initUserInfo();
  }

  async function onRouteSwitchWhenNotLoggedIn() {
    // some global init logic if it does not need to be logged in
  }
  // 动态添加单个路由
  function creteDynamicRoute({ pageId }: { pageId: string }) {
    return new Promise((resolve, reject) => {
      getNavInfo({
        pageId: pageId
      }).then((res: any) => {
        if (res.success) {
          let routeData = res.data
          if (!apiRoutes.value.some((i: any) => i.id === routeData.id)) {
            apiRoutes.value.push(routeData)
            const routes = getApiRoutes();
            addAuthRoutes([...routes]);
            handleConstantAndAuthRoutes();
          }
          let route = getRouteById(routeData.id)
          resolve(route)
        } else {
          reject('页面跳转失败，请检查是否有目标页面的访问权限')
        }
      })
    })
  }

  return {
    resetStore,
    routeHome,
    menus,
    searchMenus,
    allMenus,
    allSearchMenus,
    updateGlobalMenusByLocale,
    cacheRoutes,
    excludeCacheRoutes,
    resetRouteCache,
    breadcrumbs,
    initConstantRoute,
    isInitConstantRoute,
    initAuthRoute,
    isInitAuthRoute,
    setIsInitAuthRoute,
    getIsAuthRouteExist,
    getSelectedMenuKeyPath,
    onRouteSwitchWhenLoggedIn,
    onRouteSwitchWhenNotLoggedIn,
    creteDynamicRoute
  };
});
